package com.mgq.netty.chat.protocol;

import com.google.gson.*;

import java.lang.reflect.Type;

public class TestGson {

    public static void main(String[] args) {
        Gson gson = new GsonBuilder().registerTypeAdapter(Class.class, new ClassCodec()).create();
        System.out.println(gson.toJson(String.class));
    }

    static class ClassCodec implements JsonSerializer<Class<?>>, JsonDeserializer<Class<?>> {

        @Override
        public JsonElement serialize(Class<?> src, Type type, JsonSerializationContext jsonSerializationContext) {
            //将class name序列化成Json
            return new JsonPrimitive(src.getName());
        }

        @Override
        public Class<?> deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {

            //将JSON反序列化成class
            String str  = jsonElement.getAsString();
            try {
                return Class.forName(str);
            } catch (ClassNotFoundException e) {
                //这个方法需要一个JsonParseException异常,因此我们catch住异常时,将异常进行包装,然后返回throw
                throw new JsonParseException(e);
            }
        }
    }
}
